<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020-09-25
 * Time: 13:56
 */

namespace app\logic\traits;


use app\api\model\user\UserScoreApiModel;
use app\api\model\UserModel;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Cache;
use think\cache\driver\Redis;
trait Token
{
    public $key = 'fc6f2e74a75fd22a1224ef994c83011c';
    protected $method = 'HS256';
    protected $ex = 30;
    public function CreateToken($mobile){ //创建token
    	$slat_str=$this->getUserRedisToken(32);
    	$redis=new Redis();
    	$redis->set('user_redis_token'.$mobile,$slat_str,86400*30);//设置这个toekn的值5天内可以使用
        $payload = array(
            "exp"=> time()+86400*30,        //5天
            'data'=>array(
                'mobile'=>$mobile,
                'salt'=>$slat_str,
                'time'=>get_total_millisecond()+86400*30*100
            ),
        );
        return JWT::encode($payload, $this->key, $this->method);
    }
    
	public function getUserRedisToken($leng){
  		$s='abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ123456789/*-_+';
		$str="";
		for($i=0;$i<$leng;$i++){
			$str.=substr($s,mt_rand(0,strlen($s)-1),1);
		}
		return $str;
  	}
	
    public function GetToken($token){
        $data = JWT::decode($token, new Key($this->key, $this->method));
        if(!is_object($data) || !$data || !isset($data->data->mobile) || !isset($data->exp) || !isset($data->data->salt)){
            return [0,'token格式错误'];
        }
        $redis=new Redis();
        $mobile = $data->data->mobile; //获取openid
        $time = $data->exp;
        if($time < time()){
            return [0,'token已经失效,请重新登录'];
        }
        /*if(isset($data->data->salt) && $data->data->salt!=$redis->get('user_redis_token'.$mobile))
        {
         	return [0,'token已经失效,请重新登录.不是正常的token'];	
        }*/
        $user = UserModel::where('mobile',$mobile)->find()->toArray();
        if($user){
            if($user['is_black'] == 1){
                return [0,'在黑名单中，不能登录'];
            }
            $user['score'] =UserScoreApiModel::getScoreByUserId($user['id']);
            return [1,$user];
        }
        return [0,'不存在该会员'];
    }
}